package com.huonan.component.sftp;


import cn.hutool.extra.ftp.FtpConfig;
import cn.hutool.extra.ssh.Sftp;
import com.huonan.component.config.SftpProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.charset.Charset;

@Component
@AllArgsConstructor
@Slf4j
public class SftpClient {

    private final SftpProperties config;

    private Sftp getInstance() {
        FtpConfig ftpConfig = new FtpConfig();
        ftpConfig.setHost(config.getHost())
                .setPort(config.getPort())
                .setUser(config.getUsername())
                .setPassword(config.getPassword())
                .setCharset(Charset.defaultCharset());
        return new Sftp(ftpConfig);
    }

    public void upLoad(String srcFile, String destFile) {
        try (Sftp sftp = this.getInstance()) {
            if (!sftp.exist(destFile)) {
                sftp.mkDirs(destFile);
            }
            sftp.upload(destFile, new File(srcFile));
        }
    }
}
